package service

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-kratos/kratos/v2/log"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/trace"
	"kratosRecoverPanic/internal/biz"
	"kratosRecoverPanic/pkg/gin_encoder"
	"runtime/debug"
)

type GinService struct {
	prefix string
	log    *log.Helper
	ginBiz *biz.GinBiz
}

func NewGinService(logger log.Logger, ginBiz *biz.GinBiz) *GinService {
	return &GinService{
		prefix: "/api/gin-srv",
		log:    log.NewHelper(logger),
		ginBiz: ginBiz,
	}
}

func (g *GinService) GetPrefix() string {
	return g.prefix
}

func (s *GinService) NewServiceRoutes(g *gin.RouterGroup) {
	// Notice 可以在这里加中间件～
	g.Use(gin_encoder.GinResponseEncoderMiddleware)

	// 定义gin的路由与处理的handler
	{
		g.GET("/student-list", ginHttpHandle(s.StudentListSrv))
	}

}

func (s *GinService) StudentListSrv(c *gin.Context, ctx context.Context, res *gin_encoder.Response) {
	ctx, span := otel.Tracer("Service").Start(ctx, "StudentListSrvService", trace.WithSpanKind(trace.SpanKindProducer))
	defer func() {
		if err := recover(); err != nil {
			// trace
			stackInfo := string(debug.Stack())
			span.SetAttributes(attribute.String("errStack", stackInfo))
			// log
			errMsg := fmt.Sprintf("%v方法中发生了panic errStack: %v", "StudentListSrvService", stackInfo)
			s.log.WithContext(ctx).Error(errMsg)
			// Notice response
			res.Code = gin_encoder.ErrCodeCommon
			res.Status = false
			res.Message = "Internal Server Error!!!"
		}
		span.End()
	}()

	req := PlayerMatchListReq{}
	errBind := c.ShouldBindQuery(&req)
	if errBind != nil {
		res.Code = gin_encoder.ErrCodeCommon
		res.Status = false
		res.Message = errBind.Error()
		return
	}

	// biz层处理～可能发生panic
	ret, errGet := s.ginBiz.GetStudentList(ctx, req.Sid)
	if errGet != nil {
		res.Code = gin_encoder.ErrCodeCommon
		res.Status = false
		res.Message = errGet.Error()
		return
	}

	// Notice 没问题最后将结果传给 Data
	res.Data = ret
}

type PlayerMatchListReq struct {
	Sid string `json:"sid" form:"sid" uri:"sid" binding:"min=1,required"`
}
